package com.nz2004.controller;

import com.nz2004.entity.AdminUser;
import com.nz2004.entity.MyMsg;
import com.nz2004.entity.Result;
import com.nz2004.service.AdminUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;

import java.util.Random;


//@RestController//用了RestController
@Controller
@SessionAttributes("user")
public class AdminUserController {

    @Autowired
    private AdminUserService adminUserService;

    /**
     * 根据邮箱密码登录
     * @param email
     * @param password
     * @param model
     * @return
     */
    @GetMapping("/queryUser")
    @ResponseBody
    public Result queryAdminUserByEmail(String email, String password, Model model){
        AdminUser adminUser = adminUserService.queryAdminUserByEmail(email, password);
        //登陆成功
        if(adminUser != null){
            model.addAttribute("user",adminUser);
            return Result.getResult();
        }
        //登录失败
        return null;
    }

    @PostMapping("/insertUser")
    @ResponseBody
    public Boolean insertAdminUser(String email,String password,String real_name,Integer status){
        AdminUser adminUser = new AdminUser(null,password,email,real_name,status);
        return adminUserService.insertAdminUser(adminUser);
    }
    /*
     *@author:ReJoice
     *2020/7/2117:03
     *注销登录
     *
     */
    @RequestMapping("/logout")
    public String logout(SessionStatus status){
        status.setComplete();//移除session
        return "login";
    }

    @GetMapping("/queryAdminUsers")
    @ResponseBody
    public MyMsg queryMenus(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "2") int limit,String email,@RequestParam(defaultValue = "-1")Integer status){
        MyMsg myMsg = adminUserService.queryUsers(page,limit,email,status);
        return myMsg;
    }

    @DeleteMapping("/deleteAdminUser")
    @ResponseBody
    public Result deleteAdminUser(Integer[] ids){
        if(ids != null){
            for (int i = 0; i <ids.length ; i++) {
                int id = ids[i];
                if(adminUserService.deleteAdminUserById(id)){
                    //删除成功
                    return Result.getResult();
                }else {
                    return null;
                }
            }
        }
        return null;
    }

    @PutMapping("/updateUser")
    @ResponseBody
    public Boolean updateUser(@RequestBody AdminUser adminUser){
        return adminUserService.updateAdminUser(adminUser);
    }
}
